package com.eshop.controller;

import com.eshop.pojo.Pager;
import com.eshop.pojo.ProductInfo;
import com.eshop.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "product")
public class ProductInfoController {
    @Autowired
    private ProductInfoService service;

    @RequestMapping("list")
    @ResponseBody
    Map<String,Object> getList(ProductInfo productInfo, int rows, int page){ //接收datagrid控件返回的 页码 和 显示行数 和 productInfo对象
        //System.out.println("--------页--------"+page+","+rows+"--------多少行--------");
        //初始化分页对象
        Pager pager = new Pager();
        pager.setCurPage(page);
        pager.setPerPageRows(rows);
        //创建params对象，封装查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("productInfo", productInfo);
        //获取满足条件的商品总数
        int totalCount = service.count(params);
        //获取满足条件的商品列表
        List<ProductInfo> productInfoList = service.selectByPage(productInfo, pager);
        //创建result对象，保存查询数据结果
        Map<String,Object> result = new HashMap<>();
        result.put("total",totalCount);    //datagrid控件接收的 （固定名称）
        result.put("rows", productInfoList);
        //将结果以Json数据返回前端控制器
        return result;
    }

    @RequestMapping(value = "/addProduct",produces = "text/html;charset=UTF-8" )
    @ResponseBody
    public String addProduct(ProductInfo productInfo,HttpServletRequest request,
                             @RequestParam(value = "file",required = false) MultipartFile multipartFile){   //新增商品

        if ( upload(productInfo,request,multipartFile,true) ) {
            return "{\"success\":\"true\",\"message\":\"新增商品成功！\"}";

        } else {
            return "{\"success\":\"false\",\"message\":\"新增商品失败！\"}";
        }
    }

    @RequestMapping(value = "/off-loading", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String off_loadingProduct(@RequestParam(value = "id") String ids,
                                @RequestParam(value = "flag") int flag){                //商品下架

        try {
            service.updateStatus(ids,flag);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"success\":\"false\",\"message\":\"商品下架失败！\"}";
        }
        return "{\"success\":\"true\",\"message\":\"商品下架成功！\"}";
    }

    @RequestMapping(value = "/updateProduct", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String updateProduct(ProductInfo productInfo,
                                @RequestParam(value = "file",required = false) MultipartFile multipartFile,
                                HttpServletRequest request){                            //商品更新

        if ( upload(productInfo,request,multipartFile,false) ) {
            return "{\"success\":\"true\",\"message\":\"商品更新成功！\"}";

        } else {
            return "{\"success\":\"false\",\"message\":\"商品更新失败！\"}";
        }
    }


    //提取方法 upload
    private boolean upload(ProductInfo productInfo, HttpServletRequest request, MultipartFile multipartFile, boolean i) {
        //服务器端upload路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        //获取上传文件的文件名
        String fileName = multipartFile.getOriginalFilename();
        if ( fileName == null || fileName.equals("") ){
            fileName = "未知";
            productInfo.setPic(fileName);//设置新产品图片名
            if (i) {
                service.insertProduct(productInfo);//向数据库添加新产品
            }else
                service.edit(productInfo);
            return true;
        }
        //实例化一个File对象
        File file = new File(path, fileName);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            multipartFile.transferTo(file);//保存至物理路 径
            productInfo.setPic(fileName);//设置新产品图片名
            if (i) {
                service.insertProduct(productInfo);//向数据库添加新产品
            }else{
                System.out.println(productInfo.getId());//调试
                service.edit(productInfo);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @RequestMapping(value = "/deleteProduct", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String deleteProduct(@RequestParam(value = "id") String ids){ //商品删除
        String count = "";
        try {
            count = String.valueOf(service.deleteProduct(ids));
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"success\":\"false\",\"message\":\"商品删除失败！\"}";
        }
        return "{\"success\":\"true\",\"message\":\"删除成功！\",\"count\":" + count + "}";
    }

    @ResponseBody
    @RequestMapping("/getOnSaleProduct")
    public List<ProductInfo> getOnSaleProduct(){
        return service.getOnSaleProducts();
    }

    @RequestMapping("/getPriceById")
    @ResponseBody
    public String  getPriceById(@RequestParam("pid")String  pid){
        if (pid != null && !pid.equals("")){
            ProductInfo productInfo = service.selectById(Integer.parseInt(pid));
            return productInfo.getPrice()+"";
        }
        return "";
    }

}

